package middleware

import (
	"net/http"
	"strings"
	"time"

	// "GinAdmin/internal/model"
	// "GinAdmin/pkg/jwt"
	// "GinAdmin/pkg/logger"
	"GinAdmin/core/jwt"
	"GinAdmin/core/logger"
	"GinAdmin/model"

	"github.com/gin-gonic/gin"
)

// JWT 认证中间件
func JWT(guard *jwt.TokenGuard) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求头中的Token
		token := c.GetHeader("Authorization")

		// 检查Token是否存在
		if token == "" {
			c.JSON(http.StatusUnauthorized, model.Response{
				Code: http.StatusUnauthorized,
				Msg:  "未提供授权令牌",
			})
			c.Abort()
			return
		}

		// 移除Bearer前缀
		if strings.HasPrefix(token, "Bearer ") {
			token = token[7:]
		}

		// 解析Token
		claims, err := guard.ParseToken(token)
		if err != nil {
			logger.Error("JWT解析失败:", err)

			// 处理不同的Token错误
			var msg string
			var code int
			switch err {
			case jwt.ErrTokenExpired:
				msg = "令牌已过期"
				code = 401
			case jwt.ErrTokenNotValidYet:
				msg = "令牌尚未生效"
				code = 401
			case jwt.ErrTokenMalformed:
				msg = "令牌格式错误"
				code = 401
			default:
				msg = "授权验证失败"
				code = 401
			}

			c.JSON(http.StatusUnauthorized, model.Response{
				Code: code,
				Msg:  msg,
			})
			c.Abort()
			return
		}

		// 将用户信息保存到上下文中
		c.Set("userID", claims.ID)
		c.Set("username", claims.Username)
		c.Set("roleID", claims.RoleID)

		// 检查是否需要刷新令牌
		if claims.ExpiresAt.Time.Sub(time.Now()) < 30*time.Minute {
			newToken, err := guard.RefreshToken(token)
			if err == nil {
				// 在响应头中设置新令牌
				c.Header("X-New-Token", newToken)
			}
		}

		c.Next()
	}
}

// JWTAuth 返回JWT中间件
func JWTAuth() gin.HandlerFunc {
	return JWT(jwt.DefaultGuard)
}
